﻿/*
COPYRIGHT (C) 2011-2013 Raynald Messié

THIS FILE IS PART OF SCRUMPILOT.

SCRUMPILOT IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF 
THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

SCRUMPILOT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT
EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER
GENERAL PUBLIC LICENSE FOR MORE DETAILS.

YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH SCRUMPILOT. 
IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/

using System;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Elmah;
using ScrumPilot.Domain.BPL;
using ScrumPilot.Domain.Models;
using ScrumPilot.Helpers;

namespace ScrumPilot.Controllers
{
    [Authorize]
    public class UserController : BaseController
    {
        private UserServices _usrm;
        protected UserServices UserService { get { return _usrm ?? (_usrm = new UserServices(TFS)); } }

        [HttpGet, NoCache]
        public ActionResult UserView(Int32 id)
        {
            return View(UserService.GetUser(this.CurrentUser, id, this.CurrentCulture));
        }

        [HttpGet, NoCache]
        public JsonResult UserViewMore(Int32 id)
        {
            TFSResumeUser tfsUsr = UserService.GetTFSUserInfo(id, TFS);
            var s = new StringBuilder();
            if (tfsUsr != null && tfsUsr.ProjectRoles.Count > 0)
            {
                s.Append("<h3 class='ZeroPad'>Members of projects</h3>");
                String a = "<a href='" + Url.Action("Project", "Config") + "/{0}'>{1}</a> (";
                tfsUsr.ProjectRoles.ForEach(pr =>
                {
                    s.AppendFormat(a, pr.ID, pr.ProjectName);
                    pr.Roles.ForEach(
                        r =>
                        s.AppendFormat("<span title='{1}'>{0}</span>, ", r.Name,
                                       r.Description));
                    s.Remove(s.Length - 2, 2);
                    s.Append("), ");
                });
                s.Remove(s.Length - 2, 2);
            }
            else
                s.Append("<h3>Not Members of any projects</h3>");

            return Json(new Object[] { (tfsUsr != null ? tfsUsr.Description : ""), s.ToString() },
                        JsonRequestBehavior.AllowGet);
        }

        [HttpGet, NoCache]
        [AsyncTimeout(30000)]
        public async Task<JsonResult> GetWorkItems(Int32 id)
        {
            return Json(await (new UserServices(this.TFS, this.TfsRootUrl)).GetDetailledWorkItemsAsync(id), JsonRequestBehavior.AllowGet);
        }

        [HttpGet, NoCache]
        [AsyncTimeout(30000)]
        public async Task<JsonResult> GetBugsHistory(Int32 id)
        {
            return Json(await (new UserServices(this.TFS, this.TfsRootUrl)).HistoryBugs(id), JsonRequestBehavior.AllowGet);
        }

        [HttpGet, NoCache]
        [AsyncTimeout(30000)]
        public async Task<JsonResult> GetTasksHistory(Int32 id)
        {
            return Json(await (new UserServices(this.TFS, this.TfsRootUrl)).HistoryTasks(id), JsonRequestBehavior.AllowGet);
        }

        [HttpGet, NoCache]
        [AsyncTimeout(30000)]
        public async Task<JsonResult> GetUserHistory(Int32 id)
        {
            return Json(await (new UserServices(this.TFS, this.TfsRootUrl)).HistoryUser(id), JsonRequestBehavior.AllowGet);
        }

        [HttpGet, NoCache]
        public JsonResult CheckUsers()
        {
            return (Json(UserService.CheckUserFromTfs(), JsonRequestBehavior.AllowGet));
        }

        [HttpPost]
        public EmptyResult SynchronizeTFSUsers()
        {
            UserService.SynchronizeTFSUsers();
            return null;
        }

        [HttpGet]
        public ActionResult UsersList()
        {
            ViewBag.IsFilteredList = CurrentUserDB.FilterUsersList ? 1 : 0;
            ViewBag.isAdmin = this.CurrentUserDB.isadmin;
            return View(UserService.GetMyTeam(CurrentUser));
        }

        [HttpGet]
        public EmptyResult SetUsersListFilter(Byte type)
        {
            try
            {
                UserService.SetUsersListFilter(this.CurrentUser, type);
                return null;
            }
            catch (Exception ex)
            {
                ErrorSignal.FromCurrentContext().Raise(ex);
                throw;
            }

        }

        [HttpPost]
        public EmptyResult FollowingUser(int id, byte type)
        {
            try
            {
                UserService.FollowingUser(this.CurrentUser, id, type);
                return null;
            }
            catch (Exception ex)
            {
                ErrorSignal.FromCurrentContext().Raise(ex);
                throw;
            }
        }

        [HttpPost]
        public ActionResult Upload()
        {
            SPHelpers.UploadPhotoinDB(Request.Files["fileUpload"], int.Parse(Request.Form["id"]));

            return Request.UrlReferrer != null && Url.IsLocalUrl(Request.UrlReferrer.LocalPath)
                       ? (ActionResult)Redirect(Request.UrlReferrer.LocalPath)
                       : RedirectToAction("Index", "Home");
        }


        public override ActionResult YammerAuthorization()
        {
            this.TempData["YammerComeFrom"] = "user";
            return base.YammerAuthorization();
        }
    }
}
